package com.sali.netty.handler;

import com.sali.entity.NettyBean;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * @description:
 * @author: sali
 * @date: 2025/2/22 下午10:37.
 * @version: 1.0
 */
@Slf4j
public class DecodeHandler extends LengthFieldBasedFrameDecoder {

    public DecodeHandler(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip) {
        super(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        in = (ByteBuf) super.decode(ctx, in);
        if (in == null) {
            return null;
        }
        byte flag = in.readByte();
        int length = in.readInt();
        if (in.readableBytes() != length) {
            log.error("数据包标记长度不符合实际长度！！数据来源:[{}]", ctx.channel().remoteAddress());
        }
        byte[] bytes = new byte[length];
        in.readBytes(bytes);
        String message = new String(bytes, StandardCharsets.UTF_8);
        ReferenceCountUtil.release(in);
        return new NettyBean(flag, message);
    }

}
